//
//  NSString+help.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/9/4.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "NSString+help.h"
#import "NSData+VTMD5String.h"

@implementation NSString (help)

- (NSString *)MD5String{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] vtMD5String];
}

- (CGSize)getSizeWithFontSize:(CGFloat)fontSize maxWidth:(CGFloat)maxWidth{
    if (!IS_NSStringEx(self)) {
        return CGSizeMake(0, 0);
    }
    return [self getSizeWithFontSize:fontSize maxWidth:maxWidth maxLine:100 lineSpacing:5];
}

- (CGSize)getSizeWithFontSize:(CGFloat)fontSize maxWidth:(CGFloat)maxWidth maxLine:(NSInteger)maxLine{
    if (!IS_NSStringEx(self)) {
        return CGSizeMake(0, 0);
    }
    return [self getSizeWithFontSize:fontSize maxWidth:maxWidth maxLine:maxLine lineSpacing:5];
}

- (CGSize)getSizeWithFontSize:(CGFloat)fontSize maxWidth:(CGFloat)maxWidth maxLine:(NSInteger)maxLine lineSpacing:(CGFloat)lineSpacing{
    if (!self) {
        return CGSizeMake(0, 0);
    }
    NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = lineSpacing;
    NSDictionary* dicAttr = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName:style};
    CGSize sizeMaxLines = [self maxLineSizeWithLines:maxLine constraintSize:CGSizeMake(maxWidth, 10000) attributes:dicAttr];
    return sizeMaxLines;
}

- (CGSize)maxLineSizeWithLines:(NSInteger)lines constraintSize:(CGSize)size attributes:(NSDictionary*)dicAttr
{
    NSLayoutManager* manager = [[NSLayoutManager alloc] init];
    
    NSTextContainer* con = [[NSTextContainer alloc] initWithSize:size];
    con.lineFragmentPadding = 0;
    con.maximumNumberOfLines = lines;
    [manager addTextContainer:con];
    
    NSTextStorage* storage = [[NSTextStorage alloc] initWithString:self];
    [storage addLayoutManager:manager];
    [storage addAttributes:dicAttr range:NSMakeRange(0, self.length)];
    
    CGRect rt = [manager boundingRectForGlyphRange:NSMakeRange(0, self.length) inTextContainer:con];
    return rt.size;
}

- (CGSize)linesSizeWithLines:(NSInteger)lines constraintSize:(CGSize)size attributes:(NSDictionary*)dicAttr
{
    UIFont* font = [dicAttr objectForKey:NSFontAttributeName];
    if(!font)
        return CGSizeZero;
    
    CGFloat fMinHeight = font.pointSize*lines;
    
    CGSize sizeRet = CGSizeMake(size.width, 0);
    CGSize sizeText = CGSizeMake(size.width, 0);
    
    NSString* strTemp = self;
    BOOL bFlag = YES;
    while(bFlag)
    {
        sizeText = [strTemp maxLineSizeWithLines:lines constraintSize:size attributes:dicAttr];
        if((sizeText.height == sizeRet.height) && sizeRet.height > fMinHeight)
        {
            bFlag = NO;
            break ;
        }
        
        sizeRet = sizeText;
        strTemp = [strTemp stringByAppendingString:strTemp];
    }
    
    return sizeRet;
}

@end
